# 2022/8/6: 重构太难了 放弃了 还是按照已有的架构吧
# 这里会存在6个JSON文件
# 旧的日文名字 中文名字 中文描述
# 新的日文名字 中文名字 中文描述

from typing import List, Literal
from utils.JSON的输入和输出 import 写入json, 读取json
import requests

from utils.灵摆desc处理 import solve_P_desc

latest_data = 读取json("data/上一次的数据/Name&Desc.json")

old_name_jp: List[str] = [item["name"]["jp"] for item in latest_data]
old_name_zh: List[str] = [item["name"]["zh"] for item in latest_data]
old_desc_zh: List[str] = [item["desc"] for item in latest_data]

new_name_jp: List[str] = [
    item["name"]["jp"] for item in 读取json("output/3_res/Name&Desc.json")
]
new_name_en: List[str] = [
    item["name"]["en"] for item in 读取json("output/3_res/Name&Desc.json")
]
new_name_zh: List[str] = []
new_desc_zh: List[str] = []

jp_to_zh_dict = {
    name_jp: {"name_zh": old_name_zh[i], "desc_zh": old_desc_zh[i]}
    for i, name_jp in enumerate(old_name_jp)
}

# 用法 jp_to_zh_dict[日文名字]["name_zh"] = 中文名字
#      jp_to_zh_dict[日文名字]["desc_zh"] = 中文描述

unknown_name = []  # API也找不到的放入一个unknown列表


def getIndexOfShortestStr(list: List[str]) -> int:
    """
    获取最短的字符串的索引
    """
    index = 0
    for i, str in enumerate(list):
        if len(str) < len(list[index]):
            index = i
    return index


def api(name: str, lang: Literal["en", "jp"]):
    url = "https://tools.kooriookami.top/api/yugioh/card"
    params = {"name": name, "lang": lang}
    res = requests.get(url=url, params=params)
    name_zh, desc_zh = "", ""
    if len(res.json()["data"]):
        index = getIndexOfShortestStr([item["name"] for item in res.json()["data"]])
        # 拿到日文名字对应id
        id = res.json()["data"][index]["id"]  # 名字最短的index对应的id
        # 拿到中文名字和描述
        url = f"https://tools.kooriookami.top/api/yugioh/card/{id}"
        res = requests.get(url)
        if res.status_code == 200:
            name_zh = res.json()["data"]["name"]
            desc_zh = res.json()["data"]["desc"]
    return [name_zh, desc_zh]


def getZhWithApi(name_jp: str, name_en: str, index: int):
    """
    使用API查询中文名字和中文描述
    """
    # 需要替换的符号
    char_need_replace = [[".", "．"], [" ", "　"], ["－", "－"]]
    for char in char_need_replace:
        name_jp = name_jp.replace(char[1], char[0])
    name_zh = f"【未知】：{name_jp}"
    desc_zh = f"【未知】：{name_jp}"
    name_zh, desc_zh = api(name_jp, "jp")
    if name_zh:
        return name_zh, desc_zh
    else:  # 日文找不到 尝试英文
        name_zh, desc_zh = api(name_en, "en")
    if name_zh:
        return name_zh, desc_zh
    else:
        return ["", ""]


# 遍历新的日文名字
for index, _ in enumerate(new_name_jp):
    print(f"{index} / {len(new_name_jp)}")
    # 默认值
    new_name_zh.append(f"中文名字未知")
    new_desc_zh.append(f"中文描述未知")

    if jp_to_zh_dict.get(new_name_jp[index]):  # 能在dict中找到
        new_name_zh[-1] = jp_to_zh_dict[new_name_jp[index]]["name_zh"]
        new_desc_zh[-1] = jp_to_zh_dict[new_name_jp[index]]["desc_zh"]
    else:  # 找不到
        # 用API去找
        name_zh, desc_zh = getZhWithApi(new_name_jp[index], new_name_en[index], index)
        if not name_zh:
            unknown_name.append(
                {
                    "index": index,
                    "name": {
                        "jp": new_name_jp[index],
                        "en": new_name_en[index],
                        "zh": "",
                    },
                    "desc_zh": "",
                }
            )
        else:
            new_name_zh[-1] = name_zh
            new_desc_zh[-1] = desc_zh

# 新中文名字和中文描述输出到源文件

old_Name_Desc = 读取json("output/3_res/Name&Desc.json")

# 将 · 替换成 ・
new_name_zh = [x.replace("·", "・") for x in new_name_zh]
new_desc_zh = [x.replace("·", "・") for x in new_desc_zh]

# 处理灵摆效果
new_desc_zh = [solve_P_desc(x) if x.startswith("←") else x for x in new_desc_zh]

new_Name_Desc = [
    {
        "indx": key,
        "name": {
            "jp": old_Name_Desc[key]["name"]["jp"],
            "en": old_Name_Desc[key]["name"]["en"],
            "zh": new_name_zh[key],
        },
        "desc": new_desc_zh[key],
    }
    for key, _ in enumerate(old_Name_Desc)
]

写入json(new_Name_Desc, "output/4_res/Name&Desc.json")
写入json(unknown_name, "output/4_res/unknown_name.json")
